<template>
  <div>
    <!-- 搜索区域 -->
    <el-row style="margin-bottom: 30px" :gutter="30">
      <el-col :span="6">
        <el-input
          placeholder="请输入内容"
          v-model="queryObj.query"
          clearable
          @clear="handleSearch"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="handleSearch"
          ></el-button>
        </el-input>
      </el-col>
      <el-col :span="3">
        <el-button type="primary" @click="addUser">添加用户</el-button>
      </el-col>
    </el-row>
    <!-- 表格区域 -->
    <el-table border stripe :data="userList">
      <el-table-column type="index" width="80px"> </el-table-column>
      <el-table-column
        :prop="item.prop"
        v-for="item in userListProp"
        :key="item.prop"
        :label="item.label"
        :width="item.width"
      >
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.mg_state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changeUserState(scope.row.id, scope.row.mg_state)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="240px">
        <template slot-scope="scope">
          <!-- 编辑 -->
          <el-button
            size="mini"
            type="primary"
            @click="editUser(scope.row.id)"
            icon="el-icon-edit"
          ></el-button>
          <!-- 删除 -->
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="delUser(scope.row.id)"
          ></el-button>
          <!-- 分配权限 -->
          <el-tooltip effect="dark" content="分配权限" placement="top-end">
            <el-button
              @click="setUserRole(scope.row)"
              size="mini"
              type="warning"
              icon="el-icon-setting"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <el-pagination
      style="margin-top: 20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryObj.pagenum"
      :page-sizes="[2, 4, 5, 10]"
      :page-size="queryObj.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>
    <!-- 新增用户弹窗区域 -->
    <el-dialog
      :title="isEdit ? '编辑用户' : '添加用户'"
      :visible.sync="dialogFormVisible"
      @close="clearForm"
    >
      <el-form
        ref="addUser"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            :disabled="isEdit"
            v-model="userForm.username"
            clearable
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="!isEdit" label="密码" prop="password">
          <el-input
            v-model="userForm.password"
            show-password
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="userForm.email"
            clearable
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input
            v-model="userForm.mobile"
            clearable
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clearForm">取 消</el-button>
        <el-button type="primary" @click="handleSumbit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色的弹窗区域 -->
    <el-dialog title="修改角色" :visible.sync="roleVisible" @close="closeRole">
      <p class="userinfo">用户名:{{ userInfo.username }}</p>
      <p class="userinfo">角色名:{{ userInfo.rolename }}</p>
      <el-form>
        <el-form-item label="活动区域">
          <el-select v-model="userInfo.rid" placeholder="分配新角色">
            <el-option
              v-for="item in options.rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserListApi,
  delUserApi,
  addUserApi,
  editUserApi,
  userInfoApi,
  UserStateApi,
  UserRoleApi,
} from '../../api/user';
import { getRoleListApi } from '../../api/roles';

export default {
  data() {
    return {
      userInfo: {
        usernmae: '',
        rolename: '',
        rid: '',
        id: '',
      },
      roleVisible: false,
      queryObj: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      total: 0,
      userList: [],
      userListProp: [
        { prop: 'username', label: '姓名', width: '' },
        { prop: 'email', label: '邮箱', width: '' },
        { prop: 'mobile', label: '电话', width: '' },
        { prop: 'role_name', label: '角色', width: '' },
      ],
      isEdit: false,
      userForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      userRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        mobile: [
          {
            pattern: /^((13[0-9])|(17[0-1,6-8])|(15[^4,\\D])|(18[0-9]))\d{8}$/,
            message: '手机号格式不对',
            trigger: 'blur',
          },
        ],
        email: [
          {
            pattern:
              /^[0-9-A-Za-zd]+([-_.][0-9-A-Za-zd]+)*@([0-9-A-Za-zd]+[-.])+[A-Za-zd]{2,5}$/,
            message: '邮箱格式不对',
            trigger: 'blur',
          },
        ],
      },
      dialogFormVisible: false,
      editId: null,
      options: {
        rolesList: [],
      },
    };
  },
  created() {
    this.getUserList();
    this.getRolesList();
  },
  methods: {
    async handleRole() {
      const res = await UserRoleApi(this.userInfo.id, { rid: this.userInfo.rid });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.closeRole();
      this.getUserList();
    },
    // 关闭角色弹窗
    closeRole() {
      this.userInfo = {
        usernmae: '',
        rolename: '',
        rid: '',
        id: '',
      };
      this.roleVisible = false;
    },
    // 获取角色options
    async getRolesList() {
      const res = await getRoleListApi();
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.options.rolesList = res.data;
    },
    // 分配用户权限
    async setUserRole(row) {
      this.roleVisible = true;
      this.userInfo.username = row.username;
      this.userInfo.rolename = row.role_name;
      this.userInfo.id = row.id;
    },
    // 用户状态修改
    async changeUserState(id, state) {
      const res = await UserStateApi(id, state);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getUserList();
    },
    // 做提交
    handleSumbit() {
      this.$refs.addUser.validate((valid) => {
        if (!valid) return;
        this.isEdit ? this.onEdit() : this.onAdd();
      });
    },
    // 取消事件
    clearForm() {
      this.dialogFormVisible = false;
      this.$refs.addUser.resetFields();
    },
    // 做添加
    async onAdd() {
      const res = await addUserApi(this.userForm);
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.clearForm();
      this.getUserList();
    },
    // 做编辑
    async onEdit() {
      const params = {
        mobile: this.userForm.mobile,
        email: this.userForm.email,
      };
      const res = await editUserApi(this.editId, params);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.clearForm();
      this.getUserList();
    },
    // 新增用户
    addUser() {
      this.dialogFormVisible = true;
      this.isEdit = false;
    },
    // 编辑用户
    async editUser(id) {
      this.dialogFormVisible = true;
      this.isEdit = true;
      this.editId = id;
      const res = await userInfoApi(id);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.userForm.mobile = res.data.mobile;
      this.userForm.email = res.data.email;
      this.userForm.username = res.data.username;
    },
    // 删除用户
    delUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await delUserApi(id);
          this.$message.success(res.meta.msg);
          if (this.userList.length === 1) {
            this.queryObj.pagenum--;
            if (this.queryObj.pagenum == 1) {
              this.queryObj.pagenum = 1;
            }
          }
          this.getUserList();
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          });
        });
    },
    // 点击了搜索框的搜索
    handleSearch() {
      // 页码重置为一
      this.queryObj.pagenum = 1;
      this.getUserList();
    },
    // 获取用户列表信息
    async getUserList() {
      const res = await getUserListApi(this.queryObj);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 分页翻页和页码切换
    handleSizeChange(size) {
      this.queryObj.pagesize = size;
      this.getUserList();
    },
    handleCurrentChange(cur) {
      this.queryObj.pagenum = cur;
      this.getUserList();
    },
  },
};
</script>

<style lang='less' scoped>
.el-pagination {
  margin: 30px;
  float: right;
}
.userinfo {
  font-size: 16px;
  margin: 15px 0;
}
</style>
